import router from '@/router/index';

const configModules = import.meta.glob('../../views/*/config.js', {
  import: 'default',
  eager: true
});
const compModules = import.meta.glob('../../views/*/index.vue');

let fragments = [];

/**
 * 使用views下的文件夹构建router
 */
function addRouterByFolder() {
  const routerConfig = {
    path: '/home',
    name: 'home',
    redirect: '/home',
    children: [],
    component: () => import('@/views/home/home.vue')
  };
  // 遍历 compModules 生成router信息
  fragments = Object.entries(configModules).map(([ pagePath, meta ]) => {
    // 保留文件夹名称用作path
    const path = pagePath.replace('../../views/', '').replace('/config.js', '');
    const compPath = pagePath.replace('config.js', 'index.vue');
    return {
      path: path.toLowerCase(),
      name: meta.name,
      component: compModules[compPath],
      meta
    };
  });

  function getTime(dataStr) {
    return new Date(dataStr).getTime();
  }

  // 根据创建时间排序
  fragments.sort((a, b) => getTime(a.meta.createTime) - getTime(b.meta.createTime));
  // 设置 redirect 默认跳转到第一个页面
  routerConfig.redirect = `/home/${fragments[0].path}`;
  // 塞入到home下
  routerConfig.children = fragments;
  router.addRoute(routerConfig);
  return fragments;
}

function getRouters() {
  return fragments || addRouterByFolder();
}

function getStorage(name) {
  return window.localStorage.getItem(name) || '';
}

function setStorage(name, val) {
  window.localStorage.setItem(name, val);
}

// const storageMap = {};
// window.addEventListener('storage', (e) => {
//   if (storageMap[e.key]) storageMap[e.key](e);
// });
// function watchStorage(key, fun) {
//   storageMap[key] = fun;
// }
// function removeWatchStorage(key) {
//   storageMap[key] = null;
// }

function stringToObject(str) {
  const row = str.split(';');
  const o = {};
  row.forEach((s) => {
    const [ k, v ] = s.split(':');
    o[k] = v;
  });
  return o;
}

// let timer;

// 防抖函数
// function debounce(fun, num = 300) {
//   if (timer) clearTimeout(timer);
//   setTimeout(fun, num);
// }

export {
  addRouterByFolder,
  getRouters,
  stringToObject,
  getStorage,
  setStorage
};
